package com.liuwei.file;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.AppendFileStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.GenerateStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;

/**
 * @see https://github.com/tobato/FastDFS_Client
 * @Title: FastDFSClientWrapper.java
 * @Package com.liuwei.file
 * @Description: TODO(fastdfs集成)
 * @author 刘伟 15818570028@163.com
 * @date 2016年12月5日 下午1:40:04
 * @version V1.0
 */

@Component
public class FastDFSClientWrapper {

	private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
	/* TrackerServer接口 */
	@Autowired
	TrackerClient trackerClient;

	/* 一般文件存储接口(StorageServer接口) */
	@Autowired
	private FastFileStorageClient storageClient;

	/* 为方便项目开发集成的简单接口(StorageServer接口) */
	@Autowired
	GenerateStorageClient generateStorageClient;

	/* 支持文件续传操作的接口(StorageServer接口) */
	@Autowired
	AppendFileStorageClient appendFileStorageClient;

	/**
	 * 上传文件
	 * 
	 * @param file文件对象
	 * @return 文件访问地址
	 * @throws IOException
	 */
	public String uploadFile(MultipartFile file) throws IOException {

		StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
				FilenameUtils.getExtension(file.getOriginalFilename()), null);
		return storePath.getFullPath();
	}

	/**
	 * 将一段字符串生成一个文件上传
	 * 
	 * @param content
	 *            文件内容
	 * @param fileExtension
	 * @return
	 */
	public String uploadFile(String content, String fileExtension) {
		byte[] buff = content.getBytes(Charset.forName("UTF-8"));
		ByteArrayInputStream stream = new ByteArrayInputStream(buff);
		StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
		return storePath.getFullPath();
	}

	/**
	 * 删除文件
	 * 
	 * @param fileUrl
	 *            文件访问地址
	 * @return
	 */
	public void deleteFile(String fileUrl) {
		if (StringUtils.isEmpty(fileUrl)) {
			return;
		}
		try {
			StorePath storePath = StorePath.praseFromUrl(fileUrl);
			storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
		} catch (FdfsUnsupportStorePathException e) {
			logger.warn(e.getMessage());
		}
	}
}